package cn.yunyichina.provider.register.service.impl;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.*;
import cn.yunyichina.provider.iface.entity.base.OrderExceptionVo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.register.*;
import cn.yunyichina.provider.iface.entity.message.*;
import cn.yunyichina.provider.iface.entity.pay.PaymentJournalVo;
import cn.yunyichina.provider.register.constant.CacheConstant;
import cn.yunyichina.provider.register.utils.RegUtil;
import cn.yunyichina.provider.register.vo.PayRegisterOutVoRequest;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.ObjectParser;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import cn.yunyichina.utils.network.HttpsUtil;
import cn.yunyichina.utils.security.MD5Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/12/5.
 */
@Service
public class PayServiceImpl {

    private Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
    private Map<String,String> propertyMap_39 ;

    @Resource
    private Properties yaml;

    private final String TEMPLATECODE = "22011";
    private final String IMG_TEMPLATECODE="IMG22011";

    /**
     * 挂号支付写单 yyt.register.pay.reg.out.ack --> yyt.register.pay.reg.record.ack
     * @param data
     * @param sessionId
     * @return
     */
    public Response ackPayRegRecord(String data, String sessionId) {
        Response response = new Response();
//        logger.info("挂号支付写单 - 外部接口-->method:ackPayRegRecord,data:" + data + "！");
        PayRegisterOutVoRequest ackReuest = JsonUtils.parseObject(data,PayRegisterOutVoRequest.class);
        Log.i(LogScene.REGISTER_CUR_ORDER,"yyt.register.pay.reg.record.ack", LogParamType.REQUEST,ackReuest.getYytOrderNo(),
                "挂号支付写单,request=" +JsonUtils.toJsonString(ackReuest));

        if(ackReuest == null || StringUtils.isBlank(ackReuest.getYytOrderNo())){
            response.setResultCodeAndMessage("6000", "订单号yyt_order_no不能为空。");
        }

        /**根据订单好查出订单对象**/
        Map<String, String> ordQueryMap = new HashMap<String, String>();
        ordQueryMap.put("order_no", ackReuest.getYytOrderNo());
        Response ordResponse = BaseService.callUnderlineFromInternal(sessionId,
                "yyt.base.order.by.order.no.get", JsonUtils.toJsonString(ordQueryMap));
//        logger.info("ackPayRegOut, yyt.base.order.by.order.no.get ordResponse="+ JSON.toJSONString(ordResponse));
        if(!"0".equals(ordResponse.getResultCode())){
            logger.error("查询订单失败 " + ackReuest.getYytOrderNo());
            response.setResultCodeAndMessage("6000", "查询订单失败。");
            return response;
        }
        OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
        /**根据订单好查出订单对象 end****************/
        if(order == null){
            logger.error("查询订单为空 订单号=" +ackReuest.getYytOrderNo() + ",ordResponse="+ JSON.toJSONString(ordResponse));
            response.setResultCodeAndMessage("6000", "查询订单失败。");
        }

        order.setPayTime(StringUtils.isBlank(ackReuest.getPayTime())?DateUtils.dateToString(new Date()):ackReuest.getPayTime());
        if(StringUtils.isBlank(order.getPaymentDealId()) && StringUtils.isNotBlank(ackReuest.getPaymentDealId())){
            order.setPaymentDealId(ackReuest.getPaymentDealId());
        }

        //更新金额为支付回调回来的金额
        if(StringUtils.isNotBlank(ackReuest.getInsuranceAmount())) {
            order.setInsuranceRealAmount(ObjectParser.toInteger(ackReuest.getInsuranceAmount()));
        }
        if(StringUtils.isNotBlank(ackReuest.getPayAmount())) {
            order.setPayRealAmount(ObjectParser.toInteger(ackReuest.getPayAmount()));
        }
        if(StringUtils.isNotBlank(ackReuest.getInsuranceAmount()) && StringUtils.isNotBlank(ackReuest.getPayAmount())) {
            order.setTotalAmount(order.getInsuranceRealAmount() + order.getPayRealAmount());
        }

        if(order.getIsInsurance() == 1 && (ackReuest.getPayMode() == null || ackReuest.getPayMode() == 0)) {
            order.setPayMode((short) 27);//医保payMode 27
        }else if(ackReuest.getPayMode() != null && ackReuest.getPayMode() != 0){
            order.setPayMode(ackReuest.getPayMode());
        }
        if(StringUtils.isBlank(order.getOpenId())) {
            //锁号的时候如果有保存openId，不覆盖
            order.setOpenId(ackReuest.getOpenId());//写单的时候保存openid
        }
        order.setPayAppId(ackReuest.getPayeeAppId());

        String industrySepcDetail = "";//医保结算返回结构体
        if(ackReuest.getExtendParams() != null){
            industrySepcDetail = ackReuest.getExtendParams().getString("industry_sepc_detail");
        }
        Map<String, String> extraParamsMap = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        if(order.getIsInsurance() == 1) {
            extraParamsMap.put("industry_sepc_detail", industrySepcDetail);
            order.setExtraParams(JsonUtils.toJsonString(extraParamsMap));
        }

        //-------------------------------------写单开始事务----------------------------------------

        //请求his写单
        PayRegisterVo payRegisterVo = new PayRegisterVo();
        payRegisterVo.setHospitalCode(order.getOrgCode());
        payRegisterVo.setBranchCode(order.getBranchCode());
        payRegisterVo.setHisOrdNum(order.getHisOrderNo());
        payRegisterVo.setYytOrdNum(order.getOrderNo());
        payRegisterVo.setAgtOrdNum(order.getPaymentDealId());
        payRegisterVo.setAgtCode("");
        payRegisterVo.setPayMode(ObjectParser.toString(order.getPayMode()));
        if(order.getPayMode() !=null && 212 == order.getPayMode()){
            payRegisterVo.setPayMode("22");
        }
        payRegisterVo.setPayAmount(ObjectParser.toString(order.getPayRealAmount()));
        payRegisterVo.setPayTime(order.getPayTime());
        payRegisterVo.setIsInsurance(ObjectParser.toString(order.getIsInsurance()));
        if(StringUtils.isNotEmpty(order.getReserveNo())) {
            //预约号
            payRegisterVo.setOrderNo(order.getReserveNo());
        }
        payRegisterVo.setRegType(RegUtil.getRegType(order.getScheduleTime()));
        if(1 == order.getIsInsurance()) {
            if(order.getInsuranceMode()==4){
                //his医保
                Map<String, Object> extMap = new HashMap<String, Object>();//写单扩展参数
                extMap.put("ss_serial_no", "");//社保流水号
                extMap.put("ss_money", order.getInsuranceAmount());
                extMap.put("ss_items", extraParamsMap.get("ss_items"));
                payRegisterVo.setExtendParams(JsonUtils.toJsonString(extMap));
            }else {
                String insuredType = "", patientType = "";
                if (StringUtils.isNotBlank(industrySepcDetail)) {
                    Map<String, Object> industryMap = JsonUtils.parseObject(industrySepcDetail, Map.class);
                    Map<String, Object> registrationOrderPay = (Map<String, Object>) industryMap.get("registration_order_pay");
                    if (registrationOrderPay != null) {
                        insuredType = (String) registrationOrderPay.get("cblx");
                        patientType = (String) registrationOrderPay.get("brlx");
                    }
                }

                Map<String, Object> extMap = new HashMap<String, Object>();//写单扩展参数
                extMap.put("account_amount", order.getInsuranceRealAmount());
                extMap.put("medicare_amount", 0);//统筹写死为零
//                extMap.put("insurance_amount", order.getInsuranceAmount());
                extMap.put("insurance_amount", order.getInsuranceRealAmount());
                extMap.put("insured_type", insuredType);//参保类型 当订单为医保挂号订单时必输
                extMap.put("patient_type", patientType);//病人类型 当订单为医保挂号订单时必输
                extMap.put("industry_sepc_detail", industrySepcDetail);//医保结算返回结构体
                extMap.put("computer_no", extraParamsMap.get("computer_no"));//电脑号
                extMap.put("medical_card_no", extraParamsMap.get("medical_card_no"));//医疗证号
                payRegisterVo.setExtendParams(JsonUtils.toJsonString(extMap));
            }
        }
//        if(StringUtils.isNotBlank(order.getReserveNo())){
            //预约取号写单带多几个参数
            Map<String, String> extMap ;
            if(StringUtils.isNotBlank(payRegisterVo.getExtendParams())) {
                extMap = JsonUtils.parseObject(payRegisterVo.getExtendParams(),Map.class);
            }else{
                extMap = new HashedMap();
            }
            extMap.put("pat_card_type",String.valueOf(order.getMedicalCardType()));
            extMap.put("pat_card_no",order.getMedicalCardNo());
            extMap.put("pat_name",order.getUserName());
            extMap.put("id_card_no",order.getIdCardNo());
            extMap.put("work_id",extraParamsMap.get("work_id"));//福田中医院需求
            if(order.getOrgCode().indexOf("szsykyy") >=0 && order.getPlatformOrgAppCode().equals("yyt48fe49dbe6eb1cee")){
                extMap.put("channel","1");
            }else if(order.getOrgCode().indexOf("szsykyy") >=0 && order.getPlatformOrgAppCode().equals("yytcda5b2de00d8717c")){
                extMap.put("channel","2");
            }
            payRegisterVo.setExtendParams(JsonUtils.toJsonString(extMap));
//        }

        boolean isHisException = false ;//是否写单异常
        ResCommon<PayRegisterVoResponse> hisResponse = null;
        try{
            hisResponse = HisifaceService.getHisifaceClient().payRegister(payRegisterVo);
//            logger.info("ackPayRegOut, call hisiface payRegister request={}， response={}" ,JSONObject.toJSONString(payRegisterVo), JSONObject.toJSONString(hisResponse));
            Log.i(LogScene.REGISTER_CUR_ORDER,"yyt.register.pay.reg.record.ack", LogParamType.REQUEST,payRegisterVo.getYytOrdNum(),
                    " call hisiface payRegister request=" +JsonUtils.toJsonString(payRegisterVo));
            Log.i(LogScene.REGISTER_CUR_ORDER,"yyt.register.pay.reg.record.ack", LogParamType.RESPONSE,payRegisterVo.getYytOrdNum(),
                    " call hisiface payRegister response=" +JsonUtils.toJsonString(hisResponse));
            if ("0".equals(hisResponse.getResultCode())) {
                PayRegisterVoResponse payResponse = JsonUtils.parseObject(hisResponse.getResult(), PayRegisterVoResponse.class);

                Map<String,Object> outResultMap = new HashMap<>();//写单成功对外输出参数
                outResultMap.put("receipt_num",payResponse.getReceiptNum());
                outResultMap.put("serial_num",payResponse.getSerialNum());
                outResultMap.put("visit_address",payResponse.getVisitLocation());
                outResultMap.put("barcode",payResponse.getBarCode());
                outResultMap.put("visit_desc",payResponse.getVisitDesc());
                outResultMap.put("reserve_no",payResponse.getOrderNo());
                if(StringUtils.isNotBlank(payResponse.getExtendParams())){
                    Map<String,String> hisExtengMap = JsonUtils.parseObject(payResponse.getExtendParams(),Map.class);
                    outResultMap.put("adm_no",hisExtengMap.get("adm_no"));//福田中医院需求
                }


                /**
                 * 写单成功：
                 * 1.更新订单的状态
                 * 2.更新支付流水
                 */
                 response = doPaySuccess(order,outResultMap);

            } else {
                isHisException = true;
            }
    } catch (Exception ex) {
        logger.info("云医订单号:" + order.getOrderNo() + ",外部订单号:" + order.getOutOrderNo()
                + "写单异常，需要查询HIS是否写单成功!");
        logger.error("error", ex);
        isHisException = true;
    }
        if(isHisException){
            //异常处理流程
            response = doRegisterException(order,hisResponse!=null?hisResponse.getResultMessage():"");
        }
        return response ;
    }

    /**
     * his写单成功后处理逻辑，更改订单状态、更新流水、发送消息
     * @param order
     * @param hisMap
     */
    private Response doPaySuccess(OrderExtVo order,Map<String,Object> hisMap) {
//        order.setInsuranceRealAmount(order.getTotalAmount().intValue() - order.getPayAmount().intValue());
//        order.setPayRealAmount(order.getPayAmount());
//        order.setTotalRealAmount(order.getTotalAmount());

        order.setReceiptNum((String) hisMap.get("receipt_num"));
        order.setBarcode((String) hisMap.get("barcode"));

        String extraParamsStr = order.getExtraParams();
        Map<String, String> extraParamsMap = JsonUtils.parseObject(extraParamsStr,Map.class);
        extraParamsMap.put("serial_num",(String) hisMap.get("serial_num"));
        extraParamsMap.put("visit_address",(String) hisMap.get("visit_address"));
        extraParamsMap.put("visit_desc",(String) hisMap.get("visit_desc"));
        if(StringUtils.isNotBlank((String) hisMap.get("adm_no"))){
            extraParamsMap.put("adm_no",(String) hisMap.get("adm_no"));
        }
        order.setExtraParams(JsonUtils.toJsonString(extraParamsMap));

        order.setOrderStatusSuccess();
        order.setPayStatusPayed();//已支付
        order.setIsPayHandled(1);//支付是否通知并处理0：否，1：是
        order.setUpdateTime(DateUtils.dateToString(new Date()));
        if(StringUtils.isNotBlank((String) hisMap.get("reserve_no"))){
            order.setReserveNo((String) hisMap.get("reserve_no"));
        }



        logger.info("doPaySuccess, 写单成功，更新订单 =" +  order.getOrderNo());
        BaseService.callUnderlineFromInternal("",
                "yyt.base.order.update", JsonUtils.toJsonString(order));

        //更新支付流水
        updatePaymentJournal(order);

        Response response = new Response();
        response.setResultCodeAndMessage("0","医院出号成功");
        response.setResult(JsonUtils.toJsonString(hisMap));
        String url = yaml.getProperty("order.reg.url")+"order_no="+order.getOrderNo()+"&app_code="+order.getPlatformOrgAppCode()+"&open_id="+order.getOpenId()+"&app_id="+order.getPayAppId();
        // 消息推送
        try {
            String method = "yyt.message.msg.template.send";
            String sex = "";
            if (1 == order.getUserSex()) {
                sex = "男";
            } else if (2 == order.getUserSex()) {
                sex = "女";
            }
            String scheduleTime = order.getScheduleTime();
            if (scheduleTime != null && scheduleTime.length() > 10) {
                scheduleTime = scheduleTime.substring(0, 10);
                scheduleTime += " " + extraParamsMap.get("begin_time") + "-" + extraParamsMap.get("end_time");
            }
            Map<String, Object> dataMap = new HashedMap();
            dataMap.put("user_type", "2");
            dataMap.put("to_user", order.getOpenId());
            dataMap.put("order_no", order.getOrderNo());
            if (order.getPayMode() != null && String.valueOf(order.getPayMode()).startsWith("1")) {
                dataMap.put("platform_type", "1");
            } else if (order.getPayMode() != null && String.valueOf(order.getPayMode()).startsWith("2")) {
                dataMap.put("platform_type", "2");
            }
            dataMap.put("org_app_code", order.getPlatformOrgAppCode());
            dataMap.put("org_code", order.getOrgCode());
            dataMap.put("template_code", "21012");
            Map<String, Object> msgContent = new HashedMap();
            msgContent.put("first", "您好，您已经挂号成功。");
            msgContent.put("keyword1", order.getUserName());
            msgContent.put("keyword2", sex);
            msgContent.put("keyword3", order.getDeptName());
            msgContent.put("keyword4", order.getDoctorName());
            msgContent.put("keyword5", scheduleTime);
            String remark = "";
            if ("hysrmyy".equals(order.getOrgCode())) {
                remark = "排队号:" + extraParamsMap.get("serial_num")
                        + "\n订单号:" + order.getOrderNo()
                        + "\n就诊地址:" + extraParamsMap.get("visit_address")
                        + "\n就诊说明:" + extraParamsMap.get("visit_desc");
            }else if ("szszyy".equals(order.getOrgCode())) {
                remark = "排队号:" + (extraParamsMap.get("serial_num") == null ? "" : extraParamsMap.get("serial_num"))
                        + "\n订单号:" + order.getOrderNo();
                if (order.getReceiptNum() != null) {
                    remark += "\n发票流水号:" + (order.getReceiptNum() == null ? "" : order.getReceiptNum());
                }
                remark += "\n病人卡号:" + (order.getMedicalCardNo() == null ? "" : order.getMedicalCardNo());
                if (extraParamsMap.get("visit_address") != null) {
                    remark += "\n就诊地址:" + (extraParamsMap.get("visit_address") == null ? "" : extraParamsMap.get("visit_address"));
                }
                if (extraParamsMap.get("visit_desc") != null) {
                    remark += "\n就诊说明:" + (extraParamsMap.get("visit_desc") == null ? "" : extraParamsMap.get("visit_desc"));
                }
            }else {
                remark = "排队号:" + (extraParamsMap.get("serial_num") == null ? "" : extraParamsMap.get("serial_num"))
                        + "\n订单号:" + order.getOrderNo();
                if (order.getReceiptNum() != null) {
                    remark += "\n发票流水号:" + (order.getReceiptNum() == null ? "" : order.getReceiptNum());
                }
                if (order.getHisOrderNo() != null) {
                    remark += "\n登记号:" + (order.getHisOrderNo() == null ? "" : order.getHisOrderNo());
                }
                if (extraParamsMap.get("visit_address") != null) {
                    remark += "\n就诊地址:" + (extraParamsMap.get("visit_address") == null ? "" : extraParamsMap.get("visit_address"));
                }
                if (extraParamsMap.get("visit_desc") != null) {
                    remark += "\n就诊说明:" + (extraParamsMap.get("visit_desc") == null ? "" : extraParamsMap.get("visit_desc"));
                }
            }
            if (StringUtils.isNotBlank(order.getReserveNo())) {
                remark += "\n预约号码:" + order.getReserveNo();
            }
            if ("szsdermyy".equals(order.getOrgCode())){
                //深二自费预约成功消息定制
                msgContent.put("first", "您好，您已经预约成功。");
                if("2".equals(RegUtil.getRegType(order.getScheduleTime())) && (order.getIsInsurance() ==null || order.getIsInsurance() ==0)){
                    remark += "\n就诊卡:" + (order.getMedicalCardNo()== null ? "":order.getMedicalCardNo()) ;
                    remark += "\n若您已支付，系统会在就诊时段开始时间前两小时自动取号，可通过支付宝预约取号获取就诊信息后直接就诊；若您未支付，请于就诊时段前30分钟通过支付宝或窗口凭预约号取号；不能及时就诊请于就诊时段前2小时取消，如因个人原因超时未取号不得退号退款。本院停车位紧张，请乘坐公共交通工具就诊";
                }
            }
            msgContent.put("remark",remark);
            dataMap.put("msg_content",JsonUtils.toJsonString(msgContent));

            logger.info("doPaySuccess, 写单成功，消息推送url->"+url);
            dataMap.put("url",url);

            Response messageResponse = MessageService.callHumpFromInternal(method, JsonUtils.toJsonString(dataMap));
//            logger.info("挂号支付写单外部接口, 订单号" + order.getOrderNo() + ", 调用message模块, request={}，response={}",
//                    JsonUtils.toJsonString(dataMap),JsonUtils.toJsonString(messageResponse));
            Log.i(LogScene.REGISTER_CUR_ORDER,"yyt.register.pay.reg.record.ack", LogParamType.REQUEST,order.getOrderNo(),
                    "写单成功，调用message模块, request= request=" +JsonUtils.toJsonString(dataMap));

        } catch (Exception e) {
            logger.error("挂号支付写单外部接口, 挂号支付成功后消息推送失败:", e);
        }
        if("yytfeouwe765dhat299".equals(order.getPlatformCode())){
            notify_39(order.getOrderNo(),"1002");
        }

        Map<String,Object> getSendAppMsgTemp=new HashMap<>();
        getSendAppMsgTemp.put("platform_org_app_code",order.getPlatformOrgAppCode());
        getSendAppMsgTemp.put("platform_type",String.valueOf(Integer.valueOf(order.getPayMode())/10%10));
        getSendAppMsgTemp.put("platform_template_code",TEMPLATECODE);
        getSendAppMsgTemp.put("push_type",2);
        getSendAppMsgTemp.put("data_source","1");
        logger.info("挂号成功后获取应用消息配置, 订单号" + order.getOrderNo() + ", 调用message模块, request={}",
                JsonUtils.toJsonString(getSendAppMsgTemp));
        Response msgAppTemplateBone = MessageService.callUnderlineFromInternal("yyt.message.msg.app.template.bone.get", JsonUtils.toJsonString(getSendAppMsgTemp));
        logger.info("挂号成功后获取应用消息配置, 订单号" + order.getOrderNo() + ", 调用message模块, response={}",
                JSON.toJSONString(msgAppTemplateBone));
        if("0".equals(msgAppTemplateBone.getResultCode())){
            List<OrgAppTemplateVo> orgAppTemplateVoList = JsonUtils.parseArray(msgAppTemplateBone.getResult(), OrgAppTemplateVo.class);
            if(!CollectionUtils.isEmpty(orgAppTemplateVoList)&&orgAppTemplateVoList.size()>0){
                try {
                    for (OrgAppTemplateVo orgAppTemplateVo : orgAppTemplateVoList) {
                        if (StringUtils.isNotBlank(orgAppTemplateVo.getPushDept())) {
                            Map pushDeptMap = JSONObject.parseObject(orgAppTemplateVo.getPushDept(), Map.class);
                            if (pushDeptMap.containsKey(order.getOrgCode())) {
                                List<String> pushDeptList = Arrays.asList(pushDeptMap.get(order.getOrgCode()).toString().split(";"));
                                if (pushDeptList.contains(order.getDeptCode())) {
                                    //推送图文消息
                                    sendIMGMessage(order, orgAppTemplateVo);
                                }
                            }
                        }
                    }
                }catch (Exception e){
                    logger.error("挂号成功后获取应用消息配置失败:", e);
                }
            }
        }
        //深圳市智慧医院推送card消息
        if ("yyt48fe49dbe6eb1cee".equals(order.getPlatformCode())){
            sendCardMessage(order);
        }else{
            logger.info("非深圳智慧医院，不推送card消息，orderno=" + order.getOrderNo() + "platformcode=" + order.getPlatformCode());
        }

        if("yytc06514ff54dbe32d".equals(order.getPlatformOrgAppCode())){
            //云医通插入消息记录
            Map<String,Object> map = new HashedMap();
            map.put("id",PKGenerator.generateId());
            map.put("org_id", order.getOrgId());
            map.put("org_name",order.getOrgName());
            map.put("org_code",order.getOrgCode());
            map.put("user_id",order.getUserId());
            map.put("user_name",order.getUserName());
//            map.put("library_template_code",msgCenter.getTemplateId());
            map.put("msg_title","挂号成功通知");
            map.put("is_read",1);
//            map.put("msg_content",msgCenter.getMsgContent());

            Map<String,Object> contentMap = new HashedMap();
            List<Map<String,String>> msgTemplateContents = new ArrayList<>();
            Map<String,String> firstMap = new HashedMap();
            firstMap.put("keyword","first");
            firstMap.put("note","");
            firstMap.put("value","您好，您已经挂号成功。");
            msgTemplateContents.add(firstMap);

            Map<String,String> k1Map = new HashedMap();
            k1Map.put("keyword","姓名");
            k1Map.put("note","");
            k1Map.put("value",order.getUserName());
            msgTemplateContents.add(k1Map);

            Map<String,String> k2Map = new HashedMap();
            k2Map.put("keyword","医院");
            k2Map.put("note","");
            k2Map.put("value",order.getOrgName());
            msgTemplateContents.add(k2Map);

            Map<String,String> k3Map = new HashedMap();
            k3Map.put("keyword","挂号科室");
            k3Map.put("note","");
            k3Map.put("value",order.getDeptName());
            msgTemplateContents.add(k3Map);

            Map<String,String> k4Map = new HashedMap();
            k4Map.put("keyword","挂号医生");
            k4Map.put("note","");
            k4Map.put("value",order.getDoctorName());
            msgTemplateContents.add(k4Map);

            Map<String,String> k5Map = new HashedMap();
            k5Map.put("keyword","订单号");
            k5Map.put("note","");
            k5Map.put("value",order.getOrderNo());
            msgTemplateContents.add(k5Map);

            Map<String,String> k6Map = new HashedMap();
            k6Map.put("keyword","排队号");
            k6Map.put("note","");
            k6Map.put("value",extraParamsMap.get("serial_num"));
            msgTemplateContents.add(k6Map);

            Map<String,String> k7Map = new HashedMap();
            k7Map.put("keyword","就诊地址");
            k7Map.put("note","");
            k7Map.put("value",extraParamsMap.get("visit_address"));
            msgTemplateContents.add(k7Map);

            logger.info("~~~~~~~msgTemplateContents=" + JsonUtils.toJsonString(msgTemplateContents));
            contentMap.put("msgTemplateContents", msgTemplateContents);

            List<Map<String,String>> msgTemplateFunctions = new ArrayList<>();
            Map<String,String> funcMap = new HashedMap();
//            String detailUrl = "http://webtest.yunyichina.cn/platform/dist/pages/register/index.html#/regDetail?app_code="
//                + order.getPlatformOrgAppCode() + "&open_id=" + order.getOpenId() +"&order_no=" + order.getOrderNo();
            funcMap.put("functionCode","location='" +url + "'" );
            funcMap.put("functionName","点击查看挂号详情");
            msgTemplateFunctions.add(funcMap);

            contentMap.put("msgTemplateFunctions",msgTemplateFunctions);
            map.put("msg_content",JsonUtils.toJsonString(contentMap));
//            map.put("icon_name",msgCenter.getIconName());
//            map.put("icon_path",msgCenter.getIconPath());
            map.put("created_time",DateUtils.dateToString(new Date()));

            Response messageResponse = MessageService.callHumpFromInternal("yyt.message.messagehistory.add",JsonUtils.toJsonString(map));
            logger.info("订单号" + order.getOrderNo() + ", 调用message模块,yyt.message.messagehistory.add request={}，response={}",
                    JsonUtils.toJsonString(map),JsonUtils.toJsonString(messageResponse));

        }

        //推广端挂号成功发送短信
        if("yytc773c9f311c94c6e".equals(order.getPlatformOrgAppCode())){
            Map<String,Object> smsMap = new HashedMap();
            smsMap.put("org_code",order.getOrgCode());
            smsMap.put("to_user",order.getUserMobile());
            smsMap.put("template_code","sms_reg_001");
            smsMap.put("platform_org_app_code","yytc773c9f311c94c6e");
            Map<String,String> contentMap = JsonUtils.parseObject(JsonUtils.toJsonString(order),Map.class);
            contentMap.putAll(extraParamsMap);
            smsMap.put("msg_content",contentMap);

            Response messageResponse = MessageService.callHumpFromInternal("yyt.message.msg.sms.send",JsonUtils.toJsonString(smsMap));
            logger.info("订单号" + order.getOrderNo() + ", 调用message模块,yyt.message.msg.sms.send request={}，response={}",
                    JsonUtils.toJsonString(smsMap),JsonUtils.toJsonString(messageResponse));
        }

        return response;
    }

    public void sendIMGMessage(final OrderExtVo order,final  OrgAppTemplateVo orgAppTemplateVo) {
        logger.info("挂号成功->发送推送Bone图文消息Start");
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Map<String,String> sendDataMap=new HashedMap();
                    sendDataMap.put("user_type","2");
                    sendDataMap.put("to_user", order.getOpenId());
                    if (order.getPayMode() !=null && String.valueOf(order.getPayMode()).startsWith("1")){
                        sendDataMap.put("platform_type","1");
                    }else if (order.getPayMode() !=null && String.valueOf(order.getPayMode()).startsWith("2")){
                        sendDataMap.put("platform_type","2");
                    }
                    sendDataMap.put("org_app_code",order.getPlatformOrgAppCode());
                    sendDataMap.put("org_code",orgAppTemplateVo.getDevOrgCode());
                    //根据模板code查询图片信息
                    ImageTemplateVo imageTemplateVo = new ImageTemplateVo();
                    imageTemplateVo.setTemplateCode(orgAppTemplateVo.getLibraryTemplateCode());
                    logger.info("挂号成功->发送推送图文消息->根据模板code查询图片明细request->{}",JSON.toJSON(imageTemplateVo));
                    Response response = BaseService.callHumpFromInternal("yyt.base.image.template.by.code.get", JsonUtils.toJsonString(imageTemplateVo));
                    logger.info("挂号成功->发送推送图文消息->根据模板code查询图片明细response->{}",JSON.toJSON(response));
                    if("0".equals(response.getResultCode())){
                        List<ImageTemplateListVo> images = JsonUtils.parseArray(response.getResult(), ImageTemplateListVo.class);
                        ImageTemplateListVo imageTemplateList = null;
                        for (ImageTemplateListVo image : images) {
                            if(IMG_TEMPLATECODE.equals(image.getImageTemplateCode())){
                                imageTemplateList = image;
                                break;
                            }
                        }
                        //组装点击链接
                        if(imageTemplateList != null){
                            logger.info("imageTemplateList:" +JSON.toJSONString(imageTemplateList));
                            sendDataMap.put("image_url", imageTemplateList.getImageUrl());
                            sendDataMap.put("title", imageTemplateList.getImageTitle());
                            sendDataMap.put("url", imageTemplateList.getActionUrl());
                            sendDataMap.put("action_name", imageTemplateList.getActionName());
                            sendDataMap.put("desc", imageTemplateList.getImageContent());
                            logger.info("挂号成功->发送推送图文消息->request->{}",JSON.toJSON(sendDataMap));
                            Response responseMsg=MessageService.callHumpFromInternal("yyt.message.msg.image.send", JsonUtils.toJsonString(sendDataMap));
                            logger.info("挂号成功->发送推送图文消息->response->{}",JSON.toJSON(responseMsg));
                            if("ok".equals(responseMsg.getResult())){
                                Map<String,String> requestMap=new HashMap<>();
                                requestMap.put("id",orgAppTemplateVo.getId());
                                requestMap.put("add_type","1");
                                logger.info("挂号成功->发送推送图文消息推送次数->request->{}",JSON.toJSON(requestMap));
                                Response responseTemCout = MessageService.callUnderlineFromInternal("yyt.message.msg.app.template.count.add", JsonUtils.toJsonString(requestMap));
                                logger.info("挂号成功->发送推送图文消息推送次数->response->{}",JSON.toJSON(responseTemCout));
                            }
                        }else{
                            logger.info("无法获取图片22011模板配置参数.. templateCode：" + imageTemplateVo.getTemplateCode());
                        }
                    }else{
                        logger.info("无法获取图片模板22011配置参数.. templateCode：" + imageTemplateVo.getTemplateCode());
                    }
                }
            }).start();
        } catch (Exception e) {
            logger.error("挂号成功->发送推送Bone图文消息异常", e);
        }
    }
    /**
     * 更新支付流水
     * @param order
     */
    private void updatePaymentJournal(OrderExtVo order){

        PaymentJournalVo tmp = new PaymentJournalVo();
        tmp.setOrderNo(order.getOrderNo());
        tmp.setPayStatus((short) 1);
        logger.info("updatePaymentJournal, paymentJournal=" + JSON.toJSONString(tmp));
        Response findPaymentJournalResponse = PayService.callUnderlineFromInternal("yyt.pay.payment.journal.find",
                JsonUtils.toJsonString(tmp));
        logger.info("updatePaymentJournal, findPaymentJournalResponse=" + JSON.toJSONString(findPaymentJournalResponse));
        if ("0".equals(findPaymentJournalResponse.getResultCode())) {
//            支付流水已存在，不用更新
//            List<PaymentJournalVo> pjs = JsonUtils.parseArray(findPaymentJournalResponse.getResult(),
//                    PaymentJournalVo.class);
//            PaymentJournalVo psv = pjs.get(0);
//            psv.setHisOrderNo(order.getHisOrderNo());
//            psv.setInsuranceMode(order.getInsuranceMode());
//            logger.info("修改支付流水请求参数->" + JSON.toJSONString(psv));
//            PayService.callUnderlineFromInternal("yyt.pay.payment.journal.update", JsonUtils.toJsonString(psv));
            return ;
        }

        /*******新增支付流水****************/
        PaymentJournalVo paymentJournal=new PaymentJournalVo();
        paymentJournal.setOrgId(order.getOrgId());
        paymentJournal.setOrgName(order.getOrgName());
        paymentJournal.setOrgCode(order.getOrgCode());
        paymentJournal.setBranchId(order.getBranchId());
        paymentJournal.setBranchName(order.getBranchName());
        paymentJournal.setOrderNo(order.getOrderNo());
        paymentJournal.setOutOrderNo(order.getOutOrderNo());
        paymentJournal.setPaymentDealId(order.getPaymentDealId());
        paymentJournal.setPayAmount(order.getPayAmount());
        paymentJournal.setMedicareAmount(order.getMedicareAmount());
        paymentJournal.setAccountAmount(order.getAccountAmount());
        paymentJournal.setInsuranceAmount(order.getInsuranceAmount());
        paymentJournal.setTotalAmount(order.getTotalAmount());
        paymentJournal.setPlatformId(order.getPlatformId());
        paymentJournal.setPlatformCode(order.getPlatformCode());
        paymentJournal.setPlatformName(order.getPlatformName());
        paymentJournal.setPlatformOrgAppName(order.getPlatformOrgAppName());
        paymentJournal.setPlatformOrgAppCode(order.getPlatformOrgAppCode());
        paymentJournal.setPayAppId(order.getPayAppId());
        paymentJournal.setDealAccount("");
        paymentJournal.setAccountName("");
        paymentJournal.setPayStatus((short) 1);
        paymentJournal.setHisOrderNo(order.getHisOrderNo());
        paymentJournal.setOrderType(order.getOrderType());
        paymentJournal.setCheckStatus((short)0);
        paymentJournal.setPayTime(order.getPayTime());

        paymentJournal.setPayMode((short) order.getPayMode().intValue());

        paymentJournal.setPlatformOrgAppCode(order.getPlatformOrgAppCode());
        paymentJournal.setBranchId(order.getBranchId());
        paymentJournal.setBranchName(order.getBranchName());
        paymentJournal.setSettlementStatus((short) 0);
        if (order.getInsuranceMode() != null) {
            paymentJournal.setInsuranceMode((short) order.getInsuranceMode().intValue());
        }
        paymentJournal.setBranchId(order.getBranchId());
        paymentJournal.setBranchName(order.getBranchName());
        paymentJournal.setBranchCode(order.getBranchCode());

        logger.info("新增支付流水请求参数->" + JSON.toJSONString(paymentJournal));
        Response addPaymentJournalResponse = PayService.callUnderlineFromInternal("yyt.pay.payment.journal.add",
                JsonUtils.toJsonString(paymentJournal));
        logger.info("新增支付流水返回参数->" + JSON.toJSONString(addPaymentJournalResponse));
    }


    /**
     * 挂号支付异常处理
     * @param vo
     * @param exceptionReason 异常原因
     */
    private Response doRegisterException(OrderExtVo vo, String exceptionReason) {
        Response response ;
        vo.setOrderStatusException();//写单异常
        vo.setPayStatusPayed();//已支付
        vo.setIsPayHandled(1);////支付是否通知并处理0：否，1：是
        vo.setUpdateTime(DateUtils.dateToString(new Date()));
        logger.info("挂号写单异常, 标记为异常单" + vo.getOrderNo());
        BaseService.callUnderlineFromInternal("",
                "yyt.base.order.update", JsonUtils.toJsonString(vo));
        Map<String,String> map = new HashMap<>();
        map.put("order_no" ,vo.getOrderNo());
//        response = ackPayRegRecord(JSONObject.toJSONString(map), "");
        response = new Response();
//        if (!"0".equals(response.getResult())){
            addOrderToExceptionList(vo,exceptionReason);
            response.setResultCodeAndMessage("6004","订单号:" + vo.getOrderNo()  + "写单异常!");
//        }

        if("yytfeouwe765dhat299".equals(vo.getPlatformCode())){
            notify_39(vo.getOrderNo(),"1001");
        }
        return response;
    }

    /**
     * 挂号异常确认---外部接口 yyt.register.pay.reg.exception.ack
     * 佛一专属接口
     * @param data
     * @param sessionId
     * @return
     */
    public Response ackPayRegException(String data, String sessionId){
        Response response = new Response();
        Map<String,Object> requestVo = JsonUtils.parseObject(data, Map.class);

        // 找出对应数据库保存的挂号记录getOrderByOrderNo
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("order_no", (String) requestVo.get("order_no"));

        Response ordResponse = BaseService.callUnderlineFromInternal(sessionId, "yyt.base.order.by.order.no.get",
                JsonUtils.toJsonString(dataMap));
        logger.info("ackPayRegException, yyt.base.order.by.order.no.get ordResponse=" + JSON.toJSONString(ordResponse));
        if (!"0".equals(ordResponse.getResultCode())) {
            response.setResultCodeAndMessage("3000", "查询订单失败。");
            return response;
        }
        OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);


        AckRegisterExceptionVo hisVo = new AckRegisterExceptionVo();
        hisVo.setHospitalCode(order.getOrgCode());
        hisVo.setPatCardType(String.valueOf(order.getMedicalCardType()));
        hisVo.setPatCardNo(order.getMedicalCardNo());
        hisVo.setYytOrdNum(order.getOrderNo());
        hisVo.setHisOrdNum(order.getHisOrderNo());
        hisVo.setPayMode(String.valueOf(order.getPayMode()));
        hisVo.setPayAmount(String.valueOf(order.getPayAmount()));
        hisVo.setAgeCode("");
        hisVo.setAgtOrdNum("");

        String payDate = "";
        if (order.getPayTime() != null) {
            payDate = DateUtils.getDateStr(DateUtils.StringToDate(order.getPayTime()));
        } else if (order.getCreatedTime() != null) {
            payDate = DateUtils.getDateStr(DateUtils.StringToDate(order.getCreatedTime()));
        } else {
            payDate = "";
        }
        hisVo.setBeginDate(payDate);
        hisVo.setEndDate(DateUtils.getDateStr(new Date()));
        hisVo.setPayTime(DateUtils.dateToString(new Date()));


        ResCommon<AckRegisterExceptionVoResponse> resCommon = HisifaceService.getHisifaceClient().ackRegisterException(hisVo);
        logger.info("ackPayRegisterException, request={},response={}" , JSON.toJSONString(hisVo),JSON.toJSONString(resCommon));
        if ("0".equals(resCommon.getResultCode())) {
            logger.info("挂号异常单重新发起支付后确认his订单 成功, orderNo:{}.", new Object[] { order.getOrderNo() });
            AckRegisterExceptionVoResponse ackRegisterExceptionVoResponse = resCommon.getResult();

             /* 1.更新订单的状态*/
//            order.setHisOrderNo(ackRegisterExceptionVoResponse.getHisOrdNum());
//            order.setHisMessage(ackRegisterExceptionVoResponse.getHisMessage());
            order.setHisMessage(ackRegisterExceptionVoResponse.getVisitLocation());
            order.setBarcode(ackRegisterExceptionVoResponse.getBarCode());
            order.setReceiptNum(ackRegisterExceptionVoResponse.getReceiptNum());
//            ackRegisterExceptionVoResponse.getSerialNum()//就诊序号 // FIXME: 2017/3/2
//            ackRegisterExceptionVoResponse.getVisitDesc()//就诊说明
            order.setOutOrderNo(order.getOrderNo());

            order.setUpdateTime(DateUtils.dateToString(new Date()));
            order.setOrderStatusSuccess();
            order.setPayStatusPayed();

            BaseService.callUnderlineFromInternal(sessionId,
                    "yyt.base.order.update", JsonUtils.toJsonString(order));
            response.setResult(JSON.toJSONString(order));
            response.setResultCodeAndMessage("0", "异常确认成功");
        }else{
            response.setResultCodeAndMessage(resCommon.getResultCode(), resCommon.getResultMessage());
        }
        return response;
    }

    /**
     * 挂号支付确认接口 - 外部接口 yyt.register.pay.reg.record.ack --> yyt.register.pay.reg.record.confirm
     * 确认his是否写单成功
     * @param data
     * @param sessionId
     * @return
     */
    public Response confirmPayRegRecord(String data, String sessionId) {
        logger.info("confirmPayRegRecord, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();

        OrderExtVo orderExtVo = JsonUtils.parseObject(data, OrderExtVo.class);
        RegisterRecordsVo registerRecordsVo = new RegisterRecordsVo();
        if(StringUtils.isBlank(orderExtVo.getOrderNo())) {
            response.setResultCodeAndMessage("-1","订单号不能为空");
        }

        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("order_no", orderExtVo.getOrderNo());
//        logger.info("confirmPayRegRecord, yyt.base.order.by.order.no.get request=" + JSON.toJSONString(dataMap));
        Response ordResponse = BaseService.callUnderlineFromInternal(sessionId, "yyt.base.order.by.order.no.get",
                JsonUtils.toJsonString(dataMap));
        logger.info("confirmPayRegRecord, yyt.base.order.by.order.no.get ordResponse=" + JSON.toJSONString(ordResponse));
        if (!"0".equals(ordResponse.getResultCode())) {
            response.setResultCodeAndMessage("3002", "查询订单失败。");
            return response;
        }
        OrderExtVo vo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);

        registerRecordsVo.setHospitalCode(vo.getOrgCode());
        registerRecordsVo.setBranchCode(vo.getBranchCode());
        registerRecordsVo.setPatCardNo(vo.getMedicalCardNo());
        registerRecordsVo.setPatCardType(vo.getMedicalCardType() == null ? "1" : String.valueOf(vo.getMedicalCardType()));
//        registerRecordsVo.setOrderMode(vo.getPayMode() == null ? "0" : String.valueOf(vo.getPayMode()));
        registerRecordsVo.setOrderMode("0");//orderMode传0 查询所有
        Date scheduleDate = DateUtils.StringToDateYMD(vo.getScheduleTime());
        registerRecordsVo.setBeginDate(DateUtils.formatDate(scheduleDate));
        Calendar   calendar   =   new   GregorianCalendar();
        calendar.setTime(scheduleDate);
        calendar.add(calendar.DATE,1);//把日期往后增加一天

        registerRecordsVo.setEndDate(DateUtils.formatDate(calendar.getTime()));
        registerRecordsVo.setYytOrdNum(vo.getOrderNo());

        ResCommon<List<RegisterRecordsVoResponse>> recordResponse = HisifaceService.getHisifaceClient().getRegisterRecords(registerRecordsVo);
        logger.info("confirmPayRegRecord, call hisiface getRegisterRecords request={},response={}",
                JSONObject.toJSONString(registerRecordsVo),JSONObject.toJSONString(recordResponse));
        if (!ResCommon.SUCCESS_CODE.equals(recordResponse.getResultCode())) {
            response.setResultCodeAndMessage("6000",
                    "查询就诊卡号" + vo.getMedicalCardNo() + "对应的已挂号记录失败：" + recordResponse.getResultMessage() + "！");
            return response;
        }

        List<Map<String,Object>> registerRecordsVoResponse = JsonUtils.parseObject(recordResponse.getResult(), List.class);
        if (CollectionUtils.isEmpty(registerRecordsVoResponse)) {
            response.setResultCodeAndMessage("6002", "不存在已挂号记录！");
            return response;
        } else {
            //挂号成功
            Map<String,Object> hisMap = registerRecordsVoResponse.get(0);
            Map<String,Object> outResultMap = new HashMap<>();//写单成功对外输出参数
            outResultMap.put("receipt_num",hisMap.get("receipt_num"));
            outResultMap.put("serial_num",hisMap.get("serial_num"));
            outResultMap.put("visit_address ",hisMap.get("visit_location"));
            outResultMap.put("barcode ",hisMap.get("bar_code"));
            outResultMap.put("visit_desc ",hisMap.get("visit_desc"));
            outResultMap.put("reserve_no",hisMap.get("order_no"));
            doPaySuccess(vo,outResultMap);

            response.setResult(JsonUtils.toJsonString(outResultMap));
            response.setResult(ResCommon.SUCCESS_CODE);
        }
        logger.info("ackPayRegRecord, response=" + JsonUtils.toJsonString(response));
        return response;
    }


    /**
     * 添加到异常订单表
     * @param vo
     */
    private void addOrderToExceptionList(OrderExtVo vo,String exceptionReason) {
        boolean isAdd = true;
        try {
            Response response = BaseService.callUnderlineFromInternal("yyt.base.order.exception.by.order.no.get",
                    JsonUtils.toJsonString(vo));
//            logger.info("addOrderToExceptionList, yyt.base.order.exception.by.order.no.get response=" + JSON.toJSONString(response));
            if (!"0".equals(response.getResultCode())) {
                logger.error("doExecute, 查询异常订单失败");
            }

            OrderExceptionVo oe = JsonUtils.parseObject(response.getResult(), OrderExceptionVo.class);
            if (oe != null) {
                isAdd = false;
            }
        } catch (Exception e) {
            logger.info("查询异常单是否存在报错。");
        }

        if (isAdd) {
            logger.info("addOrderToExceptionList, 添加到异常订单表，orderNo=" + vo.getOrderNo());
            OrderExceptionVo record = new OrderExceptionVo();
            record.setBranchCode(vo.getBranchCode());
            record.setBranchId(vo.getBranchId());
            record.setBranchName(vo.getBranchName());
            record.setCreatedTime(DateUtils.dateToString(new Date()));
            record.setExceptionHandlerCount(0);
            record.setRefundHandlerCount(0);
            record.setId(PKGenerator.generateId());
            record.setIsInsurance(vo.getIsInsurance());
            record.setOrderNo(vo.getOrderNo());
            record.setOrderType(vo.getOrderType());
            record.setOrgCode(vo.getOrgCode());
            record.setOrgId(vo.getOrgId());
            record.setOrgName(vo.getOrgName());
            record.setPlatformCode(vo.getPlatformCode());
            record.setPlatformId(vo.getPlatformId());
            record.setPlatformName(vo.getPlatformName());
            record.setPlatformOrgAppCode(vo.getPlatformOrgAppCode());
            record.setUpdateTime(DateUtils.dateToString(new Date()));
            record.setHandlerResult((short) 0);
            record.setHisQueryState((short) 0);
            record.setInsuranceHandlerFlag((short) 0);
            record.setSelfPayHandlerFlag((short) 0);
            record.setExceptionReason(exceptionReason);
            record.setExceptionClass("Register-PayServiceImpl");

            CacheService.setGlobalKey(CacheConstant.CACHE_REGISTER_MODULE, CacheConstant.CACHE_REGISTER_PAY_EXCEPTION_ORDER,
                    record.getOrderNo(), JSON.toJSONString(record), CacheConstant.CACHE_NOT_EXPIRETIME);

            BaseService.callUnderlineFromInternal("", "yyt.base.order.exception.add", JsonUtils.toJsonString(record));
        }
    }

    /**
     * 39回调接口
     * @param orderNo
     * @param operateType 回调类型
    1001：支付成功，预约失败
    1002：支付成功，预约成功
    1003：退号
    1004：停诊
     */
    public void notify_39(String orderNo,String operateType){
        if(propertyMap_39 == null){
            propertyMap_39 = load39Properties();
        }

        if(CollectionUtils.isEmpty(propertyMap_39) || StringUtils.isBlank(propertyMap_39.get("url"))){
            logger.error("加载39接口调用配置文件出错");
            return;
        }
        String url = propertyMap_39.get("url");

        StringBuffer sign = new StringBuffer("operate_type=").append(operateType).append(",")
                .append("order_no=").append(orderNo).append(",")
                .append("PrivateKey=").append(propertyMap_39.get("PrivateKey")).append(",")
                .append("token=").append(propertyMap_39.get("token")).append(",")
                .append("uuid=").append(propertyMap_39.get("uuid"));
        logger.info("39签名前字符串,sign=" + sign);

        StringBuffer urlParam = new StringBuffer()
                .append("uuid=").append(propertyMap_39.get("uuid"))
                .append("&token=").append(propertyMap_39.get("token"))
                .append("&order_no=").append(orderNo)
                .append("&operate_type=").append(operateType)
                .append("&sign=").append(MD5Util.string2MD5(sign.toString()));
        logger.info("调用39接口,url=" + urlParam);

        String resp = HttpsUtil.doGet(url,urlParam.toString());
        logger.info("调用39接口,返回：" + resp);

    }

    private Map<String,String> load39Properties(){
        Map<String,String> map = new HashMap<>();
        try {
            InputStream is = PayServiceImpl.class.getClassLoader().getResourceAsStream("conf/39interface.properties");
            Properties pro = new Properties();
            pro.load(is);
            Iterator it = pro.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry entry=(Map.Entry)it.next();
                String key = (String)entry.getKey();
                String value = (String)entry.getValue();
                map.put(key,value);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 支付宝card消息推送(弃用)
     * @param order
     */
    public void regNotifySend(OrderExtVo order) {
        try {
            String method = "yyt.message.msg.reg.notify.send";
            RegNotifyVo regNotifyVo = new RegNotifyVo();

            //组装参数------------------------------------------开始
            String extraParamsStr = order.getExtraParams();
            Map<String, String> extraParamsMap = JsonUtils.parseObject(extraParamsStr,Map.class);
            String visitAddress = extraParamsMap.get("visit_address");
            String beginTime = extraParamsMap.get("begin_time");
            String scheduleTime = order.getScheduleTime().substring(0,10) + " " + new SimpleDateFormat("HH:mm:ss").format(new SimpleDateFormat("HH:mm").parse(beginTime));

            regNotifyVo.setUserId(order.getOpenId());
            regNotifyVo.setOperate("CREATE_UPDATE");
            regNotifyVo.setBizType("REG_SUCCESS");
            regNotifyVo.setOrgAppCode(order.getPlatformOrgAppCode());
            regNotifyVo.setThirdNo(order.getOrderNo());
            regNotifyVo.setLineNo("1");
            regNotifyVo.setTreatDate(scheduleTime);
            regNotifyVo.setPatientName(order.getUserName());
            regNotifyVo.setPatientCardType(String.valueOf(order.getMedicalCardType()));
            regNotifyVo.setPatientCardNo(order.getMedicalCardNo());
//            String urlParams = "?app_code=" + order.getPlatformOrgAppCode() + "&order_no=" + order.getOrderNo();
//            String url = "http://web.yunyichina.cn/platform/dist/pages/register/index.html#/regDetail";
            String urlParams = "?orderNo=" + order.getOrderNo() + "&appId=2016030701192208" + "&redirectPlatform=yytroot"
                    + "&appCode=alipay" + "&newAppCode=" + order.getPlatformOrgAppCode();
            String url = "http://jky.yunyichina.cn/mobileApp/register/infos/showOrderInfo";
            regNotifyVo.setOrderLink(url + urlParams);

            RegNotifyVo.DoctorInfo di = new RegNotifyVo.DoctorInfo();
            di.setCode(order.getDeptCode());
            di.setName(order.getDoctorName());
            di.setSex("U");
            regNotifyVo.setDoctorInfo(di);

            RegNotifyVo.DeptInfo dc = new RegNotifyVo.DeptInfo();
            dc.setCode(order.getDeptCode());
            dc.setLocation(visitAddress);
            dc.setName(order.getDeptName());
            regNotifyVo.setDeptInfo(dc);

            // 查询组织信息
            String phone = "000000";
            List<Org> orgList = new ArrayList<>();
            Org org = new Org();
            Map<String, String> orgQueryMap = new HashMap<String, String>();
            orgQueryMap.put("org_code", order.getOrgCode());
            logger.info("【支付宝card消息推送-查询组织信息】, yyt.base.branchhospital.org.list request=" + JSON.toJSONString(orgQueryMap));
            Response orgResponse = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list", JSON.toJSONString(orgQueryMap));
            logger.info("【支付宝card消息推送-查询组织信息】, yyt.base.branchhospital.org.list response=" + JSONObject.toJSONString(orgResponse));
            if (!"0".equals(orgResponse.getResultCode())) {
                logger.error("【支付宝card消息推送-查询组织信息】,查询机构信息失败");
            }else{
                orgList = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
                if (CollectionUtils.isEmpty(orgList)) {
                    logger.error("【支付宝card消息推送-查询组织信息】,不存在[org_code:" + order.getOrgCode() + "]对应的医院信息！");
                }else{
                    org = orgList.get(0);
                    if(StringUtils.isNotBlank(org.getContactTel())){
                        phone = org.getContactTel();
                    }
                }
            }
            RegNotifyVo.HosInfo hosInfo = new RegNotifyVo.HosInfo();
            hosInfo.setCode(order.getOrgCode());
            hosInfo.setName(order.getOrgName());
            hosInfo.setPhone(phone);
            regNotifyVo.setHosInfo(hosInfo);
            //组装参数------------------------------------------结束

            String messageContent = JsonUtils.toJsonString(regNotifyVo);
            logger.info("【支付宝card消息推送】, 订单号" + order.getOrderNo() + ", 调用message模块, 消息推送接口[yyt.message.msg.reg.notify.send]入参request="
                    + messageContent);
            Response messageResponse = MessageService.callHumpFromInternal(method, messageContent);
            logger.info("【支付宝card消息推送】, 订单号" + order.getOrderNo() + ", 调用message模块, 消息推送接口[yyt.message.msg.reg.notify.send]返回response="
                    + JSON.toJSONString(messageResponse));
        } catch (Exception e) {
            logger.error("【支付宝card消息推送】, 挂号支付成功后card消息推送失败:", e);
        }
    }

    /**
     * 支付宝card消息推送
     * @param order
     */
    public void sendCardMessage(OrderExtVo order) {
        try {
            String method = "yyt.message.card.message.send";
            RegCardNoticeRequestVO regCardNoticeRequestVO = new RegCardNoticeRequestVO();

            //组装参数------------------------------------------开始
            String extraParamsStr = order.getExtraParams();
            Map<String, String> extraParamsMap = JsonUtils.parseObject(extraParamsStr,Map.class);
            String visitAddress = extraParamsMap.get("visit_address");
            String beginTime = extraParamsMap.get("begin_time");
            String serial_num = extraParamsMap.get("serial_num");
            String scheduleTime = order.getScheduleTime().substring(0,10) + " " + new SimpleDateFormat("HH:mm:ss").format(new SimpleDateFormat("HH:mm").parse(beginTime));

            regCardNoticeRequestVO.setNoticeMode(RegCardNoticeRequestVO.NoticeMode.REGISTRATION);
            regCardNoticeRequestVO.setAppId("2015102000489434");
            regCardNoticeRequestVO.setTemplateId("REG_00001");
            regCardNoticeRequestVO.setUserId(order.getOpenId());
            regCardNoticeRequestVO.setAppCode("CHANNEL");
            regCardNoticeRequestVO.setDataType("REG");
            regCardNoticeRequestVO.setOperate("CREATE_UPDATE");
            regCardNoticeRequestVO.setThirdNo(order.getOrderNo());
            regCardNoticeRequestVO.setPatientName(order.getUserName());
            regCardNoticeRequestVO.setPatientCardType(String.valueOf(order.getMedicalCardType()));
            regCardNoticeRequestVO.setPatientCardNo(order.getMedicalCardNo());
            regCardNoticeRequestVO.setTreatDate(scheduleTime);
            //仕宝需求：不传排队号
//            if(StringUtils.isNotBlank(serial_num)){
//                regCardNoticeRequestVO.setLineNo(serial_num);
//            }
            regCardNoticeRequestVO.setBizType("REG_SUCCESS");

            String urlParams = "?orderNo=" + order.getOrderNo() + "&appId=2016030701192208" + "&redirectPlatform=yytroot"
                    + "&appCode=alipay" + "&newAppCode=" + order.getPlatformOrgAppCode();
            String url = "http://jky.yunyichina.cn/mobileApp/register/infos/showOrderInfo";
            regCardNoticeRequestVO.setOrderLink(url + urlParams);

            RegCardNoticeRequestVO.DoctorInfo di = new RegCardNoticeRequestVO.DoctorInfo();
            di.setCode(order.getDeptCode());
            di.setName(order.getDoctorName());
            di.setSex("U");
            regCardNoticeRequestVO.setDoctorInfo(di);

            RegCardNoticeRequestVO.DeptInfo dc = new RegCardNoticeRequestVO.DeptInfo();
            dc.setCode(order.getDeptCode());
            dc.setLocation(visitAddress);
            dc.setName(order.getDeptName());
            regCardNoticeRequestVO.setDeptInfo(dc);

            // 查询组织信息
            String phone = "000000";
            List<Org> orgList = new ArrayList<>();
            Org org = new Org();
            Map<String, String> orgQueryMap = new HashMap<String, String>();
            orgQueryMap.put("org_code", order.getOrgCode());
            logger.info("【支付宝card消息推送-查询组织信息】, yyt.base.branchhospital.org.list request=" + JSON.toJSONString(orgQueryMap));
            Response orgResponse = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list", JSON.toJSONString(orgQueryMap));
            logger.info("【支付宝card消息推送-查询组织信息】, yyt.base.branchhospital.org.list response=" + JSONObject.toJSONString(orgResponse));
            if (!"0".equals(orgResponse.getResultCode())) {
                logger.error("【支付宝card消息推送-查询组织信息】,查询机构信息失败");
            }else{
                orgList = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
                if (CollectionUtils.isEmpty(orgList)) {
                    logger.error("【支付宝card消息推送-查询组织信息】,不存在[org_code:" + order.getOrgCode() + "]对应的医院信息！");
                }else{
                    org = orgList.get(0);
                    if(StringUtils.isNotBlank(org.getContactTel())){
                        phone = org.getContactTel();
                    }
                }
            }
            RegCardNoticeRequestVO.HosInfo hosInfo = new RegCardNoticeRequestVO.HosInfo();
            hosInfo.setCode(order.getOrgCode());
            hosInfo.setName(order.getOrgName());
            hosInfo.setPhone(phone);
            regCardNoticeRequestVO.setHosInfo(hosInfo);
            //组装参数------------------------------------------结束

            String messageContent = JsonUtils.toJsonString(regCardNoticeRequestVO);
            logger.info("【支付宝card消息推送】, 订单号" + order.getOrderNo() + ", 调用message模块, 消息推送接口[yyt.message.card.message.send]入参request="
                    + messageContent);
            Response messageResponse = MessageService.callHumpFromInternal(method, messageContent);
            logger.info("【支付宝card消息推送】, 订单号" + order.getOrderNo() + ", 调用message模块, 消息推送接口[yyt.message.card.message.send]返回response="
                    + JSON.toJSONString(messageResponse));
        } catch (Exception e) {
            logger.error("【支付宝card消息推送】, 挂号支付成功后card消息推送失败:", e);
        }
    }

}
